<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}
</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅分享名称、文件名称和分享者可查）" style="width: 30%"
                clearable></el-input>
<!--      <el-button @click="Load" type="primary" style="margin-left: 10px">查询</el-button>-->
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="id" width="100" label="分享ID"/>
      <el-table-column sortable prop="name" width="180" label="分享名称"/>
<!--      <el-table-column sortable prop="fileId" width="100" label="文件ID"/>-->
      <el-table-column sortable prop="fileName" width="220" label="文件名称"/>
      <el-table-column sortable prop="code"  width="150" label="分享码"/>
      <el-table-column sortable prop="count" width="180" label="访问次数"/>
<!--      <el-table-column sortable prop="userId" width="100" label="用户ID"/>-->
      <el-table-column sortable prop="username" width="150" label="分享者"/>
      <el-table-column sortable prop="shareTime" width="280" label="分享时间"/>
      <el-table-column sortable prop="endTime" width="280" label="到期时间"/>

<!--      <el-table-column sortable fixed="right" label="操作" min-width="230">-->
<!--        <template #default="scope">-->
<!--          &lt;!&ndash;@confirm="handleDelete(scope.row.id)"代表二次确认时删除&ndash;&gt;-->
<!--          <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.id)">-->
<!--            <template #reference>-->
<!--              <el-button link :icon="Delete">删除</el-button>-->
<!--            </template>-->
<!--          </el-popconfirm>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-popconfirm title="确定取消分享吗?" @confirm="CancelShare(scope.row.id)">
            <template #reference>
              <el-button v-if="scope.row.status === '已过期'" link :icon="Delete">删    除</el-button>
              <el-button v-else type="primary" link  :icon="RemoveFilled">取消分享</el-button>
            </template>
          </el-popconfirm>
          <el-button v-show="scope.row.status !== '已过期'" link type="primary" @click="CopyLink(scope.row)" :icon="CopyDocument">复制链接</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import { reactive} from "vue";
import {Delete,RemoveFilled,CopyDocument} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';

const dataString = localStorage.getItem('data');



const data = reactive({
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  selectedRows: [], // 选中行的数组
});

const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/share/getAllShares?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("分享管理数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const handleDelete = async (Id) => {
  try {
    const res = await request.delete("/java/share/deleteById/" + Id);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};


//批量删除
const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.id); // 假设使用 id 作为唯一标识
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定删除选中的行吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      const res = await request.delete('/java/share/deleteByIds/' + selectedIds);
      console.log('批量删除返回信息：', res);
      // 成功后刷新列表
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
};


//取消分享
const CancelShare = async (Id) => {
  try {
    const res = await request.delete("/java/share/deleteById/" + Id);
    console.log(res);
  } catch (e) {
    console.log(e);
  }

  handleCurrentChange(1);
};

const CopyLink = (row) => {
  let currentUrl = location.href.substring(0, location.href.indexOf('/myShare'))
  let shareLink = currentUrl + '/downShare?code=' + row.code + '&shareId=' + row.id + '&from=' + userData.userId;
  let _input = document.createElement("input");   // 直接构建input
  _input.value = shareLink;  // 设置内容
  document.body.appendChild(_input);    // 添加临时实例
  _input.select();   // 选择实例内容
  document.execCommand("Copy");   // 执行复制
  document.body.removeChild(_input)
  ElMessage.success("复制链接成功")
}
</script>
